package com.wenx.v3system.modular.platform.controller;

import com.wenx.base.rest.BaseRestController;
import com.wenx.v3core.response.R;
import com.wenx.v3secure.annotation.RequiresPermissions;
import com.wenx.v3system.modular.platform.domain.dto.PlatformTenantDto;
import com.wenx.v3system.modular.platform.domain.query.PlatformTenantQuery;
import com.wenx.v3secure.enums.PlatformPermission;
import com.wenx.v3system.modular.platform.service.PlatformTenantService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.List;
import java.util.Map;

import static com.wenx.v3secure.annotation.RequiresPermissions.Logical.OR;

/**
 * 平台租户管理控制器
 * 
 * @author wenx
 */
@Tag(name = "平台租户管理API")
@RestController
@RequestMapping("/api/v3/platform/tenants")
public class PlatformTenantRestController extends BaseRestController<PlatformTenantDto, PlatformTenantQuery, PlatformTenantService> {

    public PlatformTenantRestController(PlatformTenantService service) {
        super(service);
    }

    @Override
    @PostMapping("/page")
    @Operation(summary = "分页查询租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R page(@RequestBody PlatformTenantQuery query) {
        return R.ok(service.page(query));
    }

    @Override
    @GetMapping("/get/{id}")
    @Operation(summary = "根据ID获取租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R get(@PathVariable Serializable id) {
        PlatformTenantDto tenant = service.getTenantById((Long) id);
        return R.ok(tenant);
    }


    @Override
    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R delete(@PathVariable Serializable id) {
        service.delete(id);
        return R.ok();
    }

    @Override
    @PutMapping("/update")
    @Operation(summary = "更新租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R update(@RequestBody PlatformTenantDto dto) {
        service.update(dto);
        return R.ok();
    }

    @GetMapping("/code/{code}")
    @Operation(summary = "根据编码查询租户", description = "根据租户编码查询租户信息")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R getTenantByCode(
            @Parameter(description = "租户编码", required = true)
            @PathVariable @NotNull String code) {
        
        PlatformTenantDto tenant = service.getTenantByCode(code);
        return R.ok(tenant);
    }

    @GetMapping("/domain/{domain}")
    @Operation(summary = "根据域名查询租户", description = "根据租户域名查询租户信息")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R getTenantByDomain(
            @Parameter(description = "租户域名", required = true)
            @PathVariable @NotNull String domain) {
        
        PlatformTenantDto tenant = service.getTenantByDomain(domain);
        return R.ok(tenant);
    }

    @Override
    @PostMapping("/add")
    @Operation(summary = "添加租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R add(@RequestBody PlatformTenantDto dto) {
        PlatformTenantDto result = service.createTenant(dto);
        return R.ok(result);
    }



    @PostMapping("/{tenantId}/status/{status}")
    @Operation(summary = "更新租户状态", description = "更新租户的状态")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R updateTenantStatus(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId,
            @Parameter(description = "租户状态", required = true)
            @PathVariable @NotNull Integer status) {
        
        service.updateTenantStatus(tenantId, status);
        return R.ok("租户状态更新成功");
    }

    @GetMapping("/expiring")
    @Operation(summary = "查询即将过期租户", description = "查询指定天数内即将过期的租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R getExpiringTenants(
            @Parameter(description = "提前天数", example = "30")
            @RequestParam(defaultValue = "30") Integer days) {
        
        List<PlatformTenantDto> tenants = service.getExpiringTenants(days);
        return R.ok(tenants);
    }

    @GetMapping("/active")
    @Operation(summary = "查询活跃租户", description = "查询指定天数内有活动的租户")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R getActiveTenants(
            @Parameter(description = "天数", example = "7")
            @RequestParam(defaultValue = "7") Integer days) {
        
        List<PlatformTenantDto> tenants = service.getActiveTenants(days);
        return R.ok(tenants);
    }

    @GetMapping("/check-code")
    @Operation(summary = "检查编码是否存在", description = "检查租户编码是否已存在")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE,PlatformPermission.PLATFORM_ALL_CODE},logical = OR)
    public R checkCodeExists(
            @Parameter(description = "租户编码", required = true)
            @RequestParam String code,
            @Parameter(description = "租户ID（编辑时排除自己）")
            @RequestParam(required = false) Long tenantId) {
        
        boolean exists = service.checkCodeExists(code, tenantId);
        return R.ok(exists);
    }

    @GetMapping("/check-domain")
    @Operation(summary = "检查域名是否存在", description = "检查租户域名是否已存在")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R checkDomainExists(
            @Parameter(description = "租户域名", required = true)
            @RequestParam String domain,
            @Parameter(description = "租户ID（编辑时排除自己）")
            @RequestParam(required = false) Long tenantId) {
        
        boolean exists = service.checkDomainExists(domain, tenantId);
        return R.ok(exists);
    }

    @PostMapping("/{tenantId}/suspend")
    @Operation(summary = "暂停租户", description = "暂停指定租户的服务")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R suspendTenant(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId) {
        
        service.updateTenantStatus(tenantId, 3); // 3-暂停
        return R.ok("租户暂停成功");
    }

    @PostMapping("/{tenantId}/activate")
    @Operation(summary = "激活租户", description = "激活指定租户的服务")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R activateTenant(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId) {
        
        service.updateTenantStatus(tenantId, 1); // 1-正常
        return R.ok("租户激活成功");
    }

    @PostMapping("/{tenantId}/disable")
    @Operation(summary = "禁用租户", description = "禁用指定租户的服务")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R disableTenant(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId) {
        
        service.updateTenantStatus(tenantId, 0); // 0-禁用
        return R.ok("租户禁用成功");
    }

    @GetMapping("/{tenantId}/usage")
    @Operation(summary = "获取租户使用情况", description = "获取租户的使用情况统计")
    @RequiresPermissions(value = {PlatformPermission.TENANT_READ_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R getTenantUsage(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId) {
        
        Map<String, Object> usage = service.getTenantUsage(tenantId);
        return R.ok(usage);
    }

    @PostMapping("/{tenantId}/extend")
    @Operation(summary = "延长租户有效期", description = "延长租户的有效期")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R extendTenantExpiry(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId,
            @Parameter(description = "延长月数", required = true)
            @RequestParam @NotNull Integer months) {
        
        service.extendTenantExpiry(tenantId, months);
        return R.ok("租户有效期延长成功");
    }

    @PostMapping("/{tenantId}/upgrade-plan")
    @Operation(summary = "升级租户套餐", description = "升级租户的套餐类型和用户数限制")
    @RequiresPermissions(value = {PlatformPermission.TENANT_ALL_CODE, PlatformPermission.PLATFORM_ALL_CODE}, logical = OR)
    public R upgradeTenantPlan(
            @Parameter(description = "租户ID", required = true)
            @PathVariable @NotNull Long tenantId,
            @Parameter(description = "套餐类型", required = true)
            @RequestParam @NotNull String planType,
            @Parameter(description = "最大用户数", required = true)
            @RequestParam @NotNull Integer maxUsers) {
        
        service.upgradeTenantPlan(tenantId, planType, maxUsers);
        return R.ok("租户套餐升级成功");
    }

}